<template>
  <div class="app-container">
    <!-- <PageTitle title="订单列表" ref="pageTitle" v-model="listQuery.city" @onChange="changeCity" /> -->
    <div class="filter-container">
      <el-input
        style="width: 160px"
        class="filter-item"
        placeholder="请输入订单编号"
        v-model="listQuery.number"
      ></el-input>
      <el-input
        style="width: 160px"
        class="filter-item"
        placeholder="请输入支付单号"
        v-model="listQuery.pay_number"
      ></el-input>

      <el-input
        style="width: 160px"
        class="filter-item"
        placeholder="请输入手机号"
        v-model="listQuery.mobile"
      ></el-input>
      <el-select
        clearable
        collapse-tags
        style="width: 160px"
        class="filter-item"
        v-model="listQuery.order_device_status"
        placeholder="请选择订单状态"
      >
        <el-option
          v-for="item in orderStatusOptions"
          :key="item.value"
          :label="item.name"
          :value="item.value"
        ></el-option>
      </el-select>
      <el-select
        clearable
        collapse-tags
        filterable
        style="width: 160px"
        class="filter-item"
        v-model="listQuery.attraction_id"
        placeholder="请选择景点"
      >
        <el-option
          v-for="item in attractionOptions"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        ></el-option>
      </el-select>

      <el-input
        style="width: 160px"
        class="filter-item"
        placeholder="请输入机柜编号"
        v-model="listQuery.cabinet_number"
      ></el-input>
      <el-input
        style="width: 160px"
        class="filter-item"
        placeholder="请输入讲解器编号"
        v-model="listQuery.device_number"
      ></el-input>

      <el-date-picker
        v-model="listQuery.rental_time"
        value-format="yyyy-MM-dd HH:mm:ss"
        type="datetimerange"
        range-separator="至"
        start-placeholder="租借开始时间"
        end-placeholder="租借结束时间"
        style="margin: 0 10px 10px 0; vertical-align: middle; width: 330px"
      >
      </el-date-picker>

      <el-button
        class="filter-item"
        type="primary"
        plain
        icon="el-icon-refresh-left"
        @click="handleReset"
        >重置</el-button
      >
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter"
        >搜索</el-button
      >
      <el-button class="filter-item" type="primary" icon="el-icon-download" @click="handleExport"
        >导出</el-button
      >
      <el-button
        id="copy-button"
        class="filter-item"
        type="primary"
        icon="el-icon-copy-document"
        @click="handleCVAll"
        >复制手机号</el-button
      >
    </div>

    <Table :data="list" :columns="columns" :loading="listLoading" @changeSelect="changeSelect">
      <template v-slot:order_device_status>
        <el-table-column label="订单状态" width="100" align="center">
          <template slot-scope="scope">
            <span
              :style="
                scope.row.order_device_status === 'returned'
                  ? 'color: #2AA23E'
                  : scope.row.order_device_status === 'leased'
                  ? 'color: #DC4A4A'
                  : ''
              "
              >{{ $orderStatus[scope.row.order_device_status] }}
            </span>
          </template>
        </el-table-column>
      </template>
      <template v-slot:use_duration>
        <el-table-column label="使用时长" width="100" align="center">
          <template slot-scope="scope">
            {{ Math.round(scope.row.use_duration / 60) }}分钟
          </template>
        </el-table-column>
      </template>

      <template v-slot:action>
        <el-table-column label="操作" minWidth="100" fixed="right">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="复制手机号" placement="top">
              <i
                class="el-icon-copy-document table-action"
                :data-clipboard-text="
                  scope.row.mobile +
                  ' ' +
                  (scope.row.rental_start_time ? scope.row.rental_start_time : '')
                "
                @click="handleCV(scope.row.mobile, scope.row.rental_start_time)"
              ></i>
              {{ scope.row.mobile }}
            </el-tooltip>
            <el-popover width="50" trigger="hover" popper-class="popover-class">
              <ul class="popover-ul">
                <template
                  v-if="
                    scope.row.order_device_status === 'leased' ||
                    scope.row.order_device_status === 'returned'
                  "
                  ><li @click="handleReturn(scope.row.number, 1)">全部退款</li>
                  <li
                    @click="handleReturn(scope.row.number, 2)"
                    v-if="scope.row.order_device_status === 'leased'"
                  >
                    正常归还
                  </li>
                  <li
                    @click="handleReturn(scope.row.number, 3)"
                    v-if="scope.row.order_device_status === 'leased'"
                  >
                    不退款归还
                  </li>
                  <li @click="$refs.manualRefund.show(scope.row)">手动选择时间退款</li></template
                >

                <li @click="$refs.refund.show(scope.row.number)">查询退款</li>
              </ul>

              <el-button type="text" slot="reference" size="mini"
                ><i class="el-icon-more"></i
              ></el-button>
            </el-popover>
          </template>
        </el-table-column>
      </template>
    </Table>
    <div class="pagination-container">
      <pagination
        :total="count"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.size"
        @pagination="fetchData"
      />
    </div>
    <ManualRefund ref="manualRefund" />
    <Refund ref="refund" />
  </div>
</template>

<script>
import { getList, exportOrders, allRefund, onlyReturn, normalReturn } from '@/api/orders'

import { PLATFORM_OPTIONS, ORDER_STATUS_OPTIONS } from '../../utils/platform'
import { getList as getAttractionList } from '@/api/attraction'
import Clipboard from 'clipboard'
import ManualRefund from './components/ManualRefund'
import Refund from './components/Refund'
import { mapGetters } from 'vuex'
/**
 * 订单状态
 * unpaid 未支付
 * cancelled 已取消
 * leased 已租借
 * returned 已归还
 */
export default {
  name: 'OrdersIndex',
  components: {
    ManualRefund,
    Refund
  },
  data() {
    return {
      list: null,
      count: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        size: 10,
        number: '',
        mobile: '',
        order_device_status: '',
        attraction_id: '',
        cabinet_number: '',
        device_number: '',
        rental_time: '',
        rental_time_start: '',
        rental_time_end: '',
        pay_number: ''
      },

      orderStatusOptions: ORDER_STATUS_OPTIONS,
      platform_options: PLATFORM_OPTIONS,
      consumeBtnShow: false,
      sn_list: [],
      attractionOptions: [],
      columns: [
        {
          type: 'index',
          align: 'center',
          label: '序号',
          width: '50'
        },

        {
          label: '景点名称',
          width: '160',
          prop: 'attraction_name',
          showOverflowTooltip: true
        },
        {
          label: '机柜编号',
          width: '150',
          prop: 'cabinet_number',
          align: 'center'
        },
        {
          label: '租借单号',
          width: '160',
          prop: 'number',
          align: 'center'
        },
        {
          label: '支付单号',
          width: '160',
          prop: 'pay_number',
          align: 'center'
        },
        {
          label: '收取费用',
          slot: 'amount',
          align: 'center'
        },

        {
          label: '订单状态',
          slot: 'order_device_status'
        },
        {
          label: '用户手机号',
          prop: 'mobile',
          width: '160',
          align: 'center'
        },
        {
          label: '租借时间',
          prop: 'rental_start_time',
          width: '160',
          align: 'center'
        },
        {
          label: '归还时间',
          prop: 'return_time',
          width: '160',
          align: 'center'
        },

        {
          label: '仓口号',
          prop: 'device_position',
          width: '100',
          align: 'center'
        },
        {
          label: '使用时长',
          prop: 'use_duration_display',
          width: '120',
          align: 'center'
        },
        {
          label: '金额',
          prop: 'amount',
          width: '100',
          align: 'center'
        },
        {
          label: '退款',
          prop: 'refund_amount',
          width: '100',
          align: 'center'
        },

        {
          label: '讲解器编号',
          prop: 'device_number',
          width: '160',
          align: 'center'
        },
        {
          label: '操作',
          slot: 'action'
        }
      ]
    }
  },
  computed: {
    ...mapGetters(['roles'])
  },

  created() {
    getAttractionList({ page: 1, size: 1000 }).then((res) => {
      this.attractionOptions = res.data.list_data
    })
    this.fetchData()
  },
  mounted() {},
  methods: {
    handleExport() {
      if (!this.listQuery.attraction_id) return this.$message.error('请选择景点')
      // if
      const query = { ...this.listQuery }
      if (query.rental_time && query.rental_time.length) {
        query.rental_time_start = query.rental_time[0]
        query.rental_time_end = query.rental_time[1]
      }
      if (!query.rental_time_start || !query.rental_time_end)
        return this.$message.error('请选择租借时间')
      exportOrders(query).then((res) => {
        import('@/vendor/Export2Excel').then((excel) => {
          excel.export_json_to_excel({
            header: res.data.header,
            data: res.data.data,
            filename: '订单列表'
          })
        })
      })
    },
    // 获取数据
    fetchData() {
      this.listLoading = true
      const query = { ...this.listQuery }
      if (query.rental_time && query.rental_time.length) {
        query.rental_time_start = query.rental_time[0]
        query.rental_time_end = query.rental_time[1]
      }
      console.log('query', query)
      delete query.rental_time

      getList(query).then((res) => {
        this.list = res.data.list_data
        this.count = res.data.paging.count
        this.listLoading = false
      })
    },
    _clipboard(clipboard) {
      clipboard
        .on('success', (e) => {
          console.log('复制成功')
          console.log(e)

          this.$message({
            message: '复制成功',
            type: 'success'
          })
          clipboard.destroy()
        })
        .on('error', (e) => {
          this.$message({
            message: '复制失败',
            type: 'error'
          })
          clipboard.destroy()
        })
    },
    handleCV(mobile, start_time) {
      const text = start_time ? `${mobile} ${start_time}` : `${mobile}`
      const clipboard = new Clipboard('.el-icon-copy-document', {
        text
      })
      this._clipboard(clipboard)
    },
    handleCVAll() {
      const copyData = this.list
        .map((item) => {
          return `${item.mobile} ${item.rental_start_time ? item.rental_start_time : ''}`
        })
        .join('\n')
      // 创建 Clipboard 实例
      const clipboard = new Clipboard('#copy-button', {
        text: () => copyData
      })
      this._clipboard(clipboard)
    },
    handleReturn(order_number, type) {
      const hasPermission = this.roles.some((role) => {
        return ['refund_operation'].includes(role)
      })
      if (!hasPermission) return this.$message.error('您没有操作退款的权限，请联系管理员。')

      const msg = type === 1 ? '全部退款' : type === 2 ? '正常归还' : '不退款归还'
      this.$confirm(`确认${msg}该订单吗`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let apiCall
          if (type === 1) {
            apiCall = allRefund({ order_number })
          } else if (type === 2) {
            apiCall = normalReturn({ order_number })
          } else {
            apiCall = onlyReturn({ order_number })
          }

          apiCall
            .then(() => {
              this.$notify({
                title: '成功',
                message: `${msg}成功`,
                type: 'success'
              })
              this.fetchData()
            })
            .catch((error) => {
              this.$notify({
                title: '失败',
                message: error.message || `${msg}失败`,
                type: 'error'
              })
            })
        })
        .catch(() => {})
    },

    // 筛选
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },
    /**
     * @description:
     * @return {*}
     */
    handleReset() {
      this.listQuery = {
        page: 1,
        size: 10,
        number: '',
        mobile: '',
        order_device_status: '',
        attraction_id: '',
        cabinet_number: '',
        device_number: '',
        rental_time_start: '',
        rental_time_end: '',
        pay_number: ''
      }
      this.fetchData()
    },
    /**
     * @description: 订单详情
     * @param {*} sn
     * @return {*}
     */
    handleDetail(sn, can_consume) {
      this.$router.push({ path: `/orders/detail/${sn}`, query: { can_consume } })
    },

    /**
     * @description: 判断是否可选
     * @return {*}
     */
    checkSelectable(row) {
      return row.order_status == 1 && !!row.can_consume
    },
    /**
     * @description: 选择行
     * @return {*}
     */
    changeSelect(e) {
      this.consumeBtnShow = !!e.length > 0
      this.sn_list = e.map((item) => item.sn)
    }
  }
}
</script>
<style scoped lang="less">
.filter-container {
  justify-content: flex-start !important;
  flex-wrap: wrap;
}
.el-button {
  margin-bottom: 5px;
  margin-left: 0;
  margin-right: 5px;
}

.popover-ul {
  padding: 0;
  margin: 0;
  padding: 10px 0;
  li {
    list-style: none;
    line-height: 36px;
    cursor: pointer;
    padding: 0 15px;
    &:hover {
      background-color: #f0f3ff;
      color: #1677ff;
    }
  }
}
</style>
<style>
.popover-class {
  padding: 0 !important;
}
</style>
